//这个路由  有登录  注册 接口
//加载数据库
const db = require('../db')
//加载加密模块
const utils = require('utility')
//加载token模块
const jwt = require('jsonwebtoken')
// 加载express
const express = require('express')

//创建router对象
const router = express.Router()

//注册接口
router.post('/reguser', (req, res) => {
    let { username, password } = req.body
    //对密码进行加密
    password = utils.md5(password)
    //判断用户名是否又重复的
    db(`SELECT * FROM user WHERE username='${username}'`, (e, r) => {
        if (e) throw e
        //如果获取不到到,就会返回一个空数组,然后判断
        if (r.length > 0) {
            res.send({ status: 1, message: '你注册的用户名已被占用' })
        } else {
            // 添加到数据库
            db(`insert into user set username='${username}',password='${password}'`, (err, re) => {
                if (err) throw err
                res.send({ status: 0, message: '注册成功' })
            })
        }
    })
})


//登录接口
router.post('/login', (req, res) => {
    //接收发过来的请求的值
    let username = req.body.username
    let password = utils.md5(req.body.password)
    // console.log(password);
    //验证账号密码
    db(`SELECT * FROM user WHERE username='${username}' and password='${password}'`, (e, r) => {
        if (e) throw e
        if (r.length > 0) {
            let token = jwt.sign({ id: r[0].id }, 'ssdsdas', { expiresIn: '2h' })
            res.send({ status: 0, message: '登录成功', token: 'Bearer ' + token })
        } else {
            res.send({ status: 1, message: '你输入的账号或者密码有误' })
        }
    })
    //做出响应
})

//导出router
module.exports = router